package com.leyou.sms.listener;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.leyou.common.enums.LyExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.constants.MQConstants;
import com.leyou.sms.utils.SmsUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SmsListener {

    @Autowired
    private SmsUtils smsUtils;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name= MQConstants.Queue.SMS_QUEUE,durable = "true"),
            exchange = @Exchange(name = MQConstants.Exchange.SMS_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.SMS_KEY
    ))
    public void smsListen(Map<String,String> map){

        if (map == null) {
            return;
        }

        //调用工具类发送短信
        String phone = map.get("phone");
        String code = map.get("code");
        try {
            SendSmsResponse response = smsUtils.sendSms(phone, "{\"code\":" + code + "}");
            System.out.println("Code:"+response.getCode());
        } catch (ClientException e) {
            e.printStackTrace();
            throw new LyException(LyExceptionEnum.INVALID_VERIFY_CODE);
        }

    }

}
